package cluster

import akka.actor.typed.ActorSystem
import akka.actor.typed.scaladsl.Behaviors
import akka.cluster.typed.Cluster
import com.typesafe.config.ConfigFactory

/**
 * Created by yz on 30/9/2020
 */
object App {

  object RootBehavior {

    def apply() = Behaviors.setup[Nothing] { ctx =>
      val cluster = Cluster(ctx.system)
      if (cluster.selfMember.hasRole("backend")) {
        ctx.spawn(MyDb(), s"myDb")
      }
      if (cluster.selfMember.hasRole("frontend")) {
        ctx.spawn(Client(), s"Frontend")
      }
      Behaviors.empty
    }

  }

  def main(args: Array[String]): Unit = {
    if (args.isEmpty) {
      startup("backend", 25251)
      startup("frontend", 25252)
    } else {
      startup(args(0), args(1).toInt)
    }

  }

  def startup(role: String, port: Int) = {
    val config = ConfigFactory.parseString(
      s"""
        akka.remote.artery.canonical.port=$port
        akka.cluster.roles = [$role]
         """).withFallback(ConfigFactory.load("myDb"))
    println(config.getString("akka.actor.provider"))
    ActorSystem[Nothing](RootBehavior(), "ClusterSystem", config)

  }

}
